/*
 * IssueTicketCommand.java
 *
 * Created on October 3, 2007, 8:52 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package drb;

import java.io.BufferedReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Asger
 */
public class IssueTicketCommand extends PromptingCommand {
    
    private FindFreeConnectionsCommand findConnectionsCmd;
    
    public Passenger passenger;
    
    /** Creates a new instance of IssueTicketCommand */
    public IssueTicketCommand(BufferedReader input, FindFreeConnectionsCommand findConnectionsCmd) {
        super(input);
        this.findConnectionsCmd = findConnectionsCmd;
    }
    
    public void execute() throws SQLException {
        
        System.out.println("-------------------------------");
        
        ArrayList<TrainRoute> routes = findConnectionsCmd.getSelectedRoutes();
        
        if (routes.size() == 0)
        {
            System.out.println("No routes are selected. Starting 'find-connections' command:");
            findConnectionsCmd.execute();
        }
        else
        {
            System.out.println("You currently have " + routes.size() + " routes selected.");
            boolean selectNew = promptYesNo("Do you want to select new routes?", false);
            if (selectNew) {
                findConnectionsCmd.execute();
            } else {
                for (TrainRoute r : routes) {
                    System.out.println("-------------------------------");
                    r.printDetails( findConnectionsCmd.isFirstClassSelected() );
                }
            }
        }
        System.out.println("-------------------------------");
        
        routes = findConnectionsCmd.getSelectedRoutes();
        if (routes.size() == 0)
        {
            return; // No routes were found, cancel.
        }
        
        boolean firstClass = findConnectionsCmd.isFirstClassSelected();
        
        int index = 0;
        
        // Do not bother asking if only one connection is available. (ie. "Please enter a number between 1 and 1")
        if (routes.size() > 1)
        {
            System.out.println("Select the Id of the route you wish to purchase a ticket for (1-"+routes.size()+"):");
            index = promptInt(1, routes.size()) - 1;
        }
        else
        {
            boolean wantTicket = promptYesNo("Do you want this ticket?", true);
            if (!wantTicket)
            {
                System.out.println("No ticket was issued");
                System.out.println("-------------------------------");
                return;
            }
        }
        
        // Get the selected train route
        TrainRoute route = routes.get(index);
        
        char fcChar = firstClass? 'A':'B';
        
        // Start transaction here before we get the ticket ID
        connection.setAutoCommit(false);
        
        String sql = "SELECT MAX(ticket_id) AS max_ticket_id FROM tickets";
        ResultSet result = connection.createStatement().executeQuery(sql);
        
        int ticketId = 1;
        if (result.first())
        {
            ticketId = result.getInt("max_ticket_id") + 1;
        }
        
        // Create a new ticket for the passenger
        sql = "INSERT INTO tickets (ticket_id, class, ticket_price, passenger_cpr) VALUES " +
                "("+ticketId+", '"+fcChar+"', "+route.getPrice(firstClass)+", "+passenger.cpr+")";
        connection.createStatement().execute(sql);
        
        // Add the connections to the ticket
        for (TrainConnection con : route.connections) {
            sql = "INSERT INTO ticketdue (ticket_id, departure, to_name, from_name, train_number) VALUES " +
                    "("+ticketId+", "+con.departure+", '"+escapeSQL(con.to)+"', '"+escapeSQL(con.from)+"', "+con.trainNumber+")";
            connection.createStatement().execute(sql);
        }
        
        connection.commit();
        connection.setAutoCommit(true); // End transaction
        
        System.out.println("-------------------------------");
        System.out.println("Your ticket has been created.");
        System.out.println("-------------------------------");
        
        Ticket ticket = new Ticket();
        ticket.id = ticketId;
        ticket.route = route;
        ticket.passenger = passenger;
        ticket.price = route.getPrice(firstClass);
        ticket.firstClass = firstClass;
        
        ticket.printDetails();
        ticket.printTransfers();
        
        System.out.println("-------------------------------");
        
    }
}












